<?php

declare(strict_types=1);

namespace App\Service;

use App\Exception\BusinessException;
use App\Lib\BaseValidator;
use App\Lib\ValidateException;
use App\Repository\User\UserProfilesRepository;
use Hyperf\Di\Annotation\Inject;

class UserProfilesService
{
    #[Inject]
    private UserProfilesRepository $userProfilesRepository;

    /**
     * 补全用户资料
     * 该方法用于UserCreated事件处理回调
     * @param array $data
     */
    public function initUserProfiles(array $data)
    {
        $this->userProfilesRepository->create($data);
    }

    /**
     * 获取用户资料
     * @param string $user_id
     * @return array
     */
    public function getUserProfiles(string $user_id): array
    {
        return $this->userProfilesRepository->getDataById($user_id);
    }

    /**
     * 跟新用户详细信息
     * @param array $data
     * @param string $user_id
     * @return void
     */
    public function updateUserProfiles(array $data, string $user_id): void
    {
        $data = $data['profile'];

        // 数据验证
        try {
            BaseValidator::make($data, [
                'bio' => 'string|max:2000',
                'website' => 'url|max:500',
                'location' => 'max:100',
                'company' => 'max:100'
            ], [
                'bio.max' => '个人简介过长，不能超过2000字符',
                'website.url' => '网站格式有误！',
                'website.max' => '网站过长！',
                'location.max' => '地区过长！',
                'company.max' => '公司过长！'
            ]);
        } catch (ValidateException $e) {
            throw new BusinessException(BaseValidator::$error, 0);
        }

        $this->userProfilesRepository->updateData($data, $user_id);
    }

}